import useIntlCustom from '@/hooks/useIntlCustom';
// import store from '@/store';
import { Form, Input, Modal, Select } from 'antd';
import { FC, useEffect } from 'react';

interface AddOrgModalProps {
  visible: boolean;
  orgParentDetail: any;
  onCancel: () => void;
  onOk: (values: AddOrgFormValues) => void;
  loading: boolean;
  prefix: string;
  orgTreeData: any[];
}

export interface AddOrgFormValues {
  departmentId: string;
  departmentName: string;
  parentId: string;
  orgParentDetail: any;
}

const AddOrgModal: FC<AddOrgModalProps> = ({
  visible,
  onCancel,
  onOk,
  orgParentDetail,
  loading,
  prefix,
  orgTreeData,
}) => {
  const [form] = Form.useForm<AddOrgFormValues>();
  const { translate } = useIntlCustom();

  // 从树形数据中提取所有机构选项
  const extractOrgOptions = (nodes: any[]): any[] => {
    let options: any[] = [];
    nodes.forEach((node) => {
      options.push({
        departmentId: node.departmentId,
        departmentName: node.departmentName,
      });
      if (node.children && node.children.length > 0) {
        options = options.concat(extractOrgOptions(node.children));
      }
    });
    return options;
  };

  const orgList = extractOrgOptions(orgTreeData);
  const parentOrgOptions = orgList.map((opt: any) => ({
    label: `${opt.departmentId}-${opt.departmentName}`,
    value: opt.departmentId,
  }));
  // 监听 orgParentDetail 变化，更新表单值
  useEffect(() => {
    if (orgParentDetail?.key) {
      form.setFieldsValue({
        parentId: orgParentDetail.key,
      });
    }
  }, [orgParentDetail, form, parentOrgOptions]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      await onOk(values);
      // 成功后重置表单
      form.resetFields();
    } catch (error) {
      // 验证失败不做处理
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <Modal
      title={translate(prefix, 'addOrg')}
      open={visible}
      centered
      onCancel={handleCancel}
      onOk={handleOk}
      maskClosable={false}
      confirmLoading={loading}
    >
      <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
        <Form.Item
          label={translate(prefix, 'departmentId')}
          name="departmentId"
          rules={[{ required: true, message: translate(prefix, 'orgIdRequired') }]}
        >
          <Input placeholder={translate(prefix, 'orgIdPlaceholder')} />
        </Form.Item>
        <Form.Item
          label={translate(prefix, 'departmentName')}
          name="departmentName"
          rules={[{ required: true, message: translate(prefix, 'orgNameRequired') }]}
        >
          <Input placeholder={translate(prefix, 'orgNamePlaceholder')} />
        </Form.Item>
        <Form.Item
          label={translate(prefix, 'parentOrgId')}
          name="parentId"
          rules={[{ required: true, message: translate(prefix, 'parentOrgRequired') }]}
        >
          <Select
            labelInValue
            placeholder={translate(prefix, 'parentOrgPlaceholder')}
            disabled={orgParentDetail?.key}
            showSearch
          >
            {parentOrgOptions.map((opt) => (
              <Select.Option key={opt.value} value={opt.value} label={opt.label}>
                {opt.label}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddOrgModal;
